package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @DubboReference
    private UserService userService;

    /**
     * @Author: 位帅帅
     * @Date: 16:56 2021/1/11
     * @Params: [user]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 用户登录
     */
    @PreAuthorize("hasAuthority('USER_QUERY')")
    @RequestMapping("login")
    public Result login(@RequestBody User user) {
        log.info("[用户-登录]param: {}", user);
        User user2 = userService.selectByUserName(user.getUsername());
        log.info("[用户-登录]result: {}", user2);
        if (null == user2) {
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        if (!user.getPassword().equals(user2.getPassword())) {
            return new Result(false, MessageConst.LOGIN_FAIL);
        } else {
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
    }

    /**
     * @Author: 位帅帅
     * @Date: 13:52 2021/1/14
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 获取用户名
     */
    @GetMapping("getUsername")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }

    @RequestMapping("loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("loginFail")
    public Result loginFail() {
        return new Result(false, MessageConst.LOGIN_FAIL);
    }
}
